package com.qiuxi.modules.system.domain.department;

import com.qiuxi.modules.system.repository.DepartmentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;
import java.util.Random;

import static com.cartisan.utils.AssertionUtil.requirePresent;

/**
 * @author oogundam
 * @date 2020/1/10 16:01
 **/
@Service
public class DepartmentCodeGenerator {

    private final DepartmentRepository departmentRepository;

    public DepartmentCodeGenerator(DepartmentRepository departmentRepository){
        this.departmentRepository = departmentRepository;
    }

    public String generate(Long parentId, Integer type){
        String parentPart = generateParentPart(parentId);

        String typePart = generateTypePart(type);

        String randPart = generateRandomPart();

        return parentPart+typePart+randPart;
    }

    private String generateRandomPart() {
        return String.valueOf(new Random().nextInt(6));
    }

    private String generateTypePart(Integer type) {
        String typePart = "";
        if(type==1){
            typePart = "A";
        }
        else if(type==2){
            typePart = "B";
        }
        return typePart;
    }

    private String generateParentPart(Long parentId) {
        String parentPart = "";
        if(parentId!=0){
            Department department = requirePresent(this.departmentRepository.findById(parentId));
            parentPart = department.getCode()+"_";
        }
        return parentPart;
    }
}
